//
//  CHBDiscoverSearchView.swift
//  weibo.chb
//
//  Created by 褚红彪 on 16/1/20.
//  Copyright © 2016年 chuhongbiao. All rights reserved.
//

import UIKit

class CHBDiscoverSearchView: UIView,UITextFieldDelegate {
    //不能这么写有可能它拿不到searchView，因为是用xib加载的，这个时候还没有加载出来
    /*@IBInspectable var cornerRadius: CGFloat{
        get{
            return searchView.layer.cornerRadius
        }
        set{
            searchView.layer.cornerRadius = newValue
            searchView.layer.masksToBounds = true
        }
    }*/
    @IBOutlet weak var searchView: UITextField!
    @IBOutlet weak var cancelBtn: UIButton!
    @IBOutlet weak var searchViewRightCons: NSLayoutConstraint!
    class func discoverSearchView() -> CHBDiscoverSearchView {
        return NSBundle.mainBundle().loadNibNamed("CHBDiscoverSearchView", owner: nil, options: nil).last as! CHBDiscoverSearchView
    }
    override func awakeFromNib() {
            let leftView = UIImageView(image: UIImage(named: "searchbar_textfield_search_icon"))
            leftView.frame = CGRectMake(0, 0, searchView.frame.height, searchView.frame.height)
            leftView.contentMode = .Center
            searchView.leftView = leftView
            searchView.leftViewMode = .Always
    }
    @IBAction func cancelBtnClick(sender: AnyObject) {
        searchViewRightCons.constant = 0
        UIView.animateWithDuration(0.5, animations: { () -> Void in
            self.searchView.layoutIfNeeded()
            }) { (_) -> Void in
                searchView.resignFirstResponder()
        }
    }
    func textFieldDidBeginEditing(textField: UITextField) {
        //当开始编辑的时候文本框往左缩，把取消按钮显示出来
        searchViewRightCons.constant = cancelBtn.frame.width
        UIView.animateWithDuration(0.5) { () -> Void in
            //要执行动画效果只需要写如下的代码就可以了
            self.searchView.layoutIfNeeded()
        }
    }
}
